#include "power_up.h"
#include "mmgr.h"
#include <cassert>

PowerUp::PowerUp() : m_CurrentEffects(0)
{
}

PowerUp::~PowerUp()
{
}

bool PowerUp::AddEffect(unsigned long EffectID, float Duration)
{
	for (unsigned int i = 0; i < m_Effects.size(); i++)
	{
		if (m_Effects[i].EffectID == EffectID)
		{
			if ((Duration < 0.0f) || (m_Effects[i].Duration < Duration))
				m_Effects[i].Duration = Duration;

			return false;
		}
	}

	EFFECT_DATA effect;
	effect.EffectID = EffectID;
	effect.Duration = Duration;

	m_Effects.push_back(effect);
	m_CurrentEffects |= EffectID;
	return true;
}

bool PowerUp::RemoveEffect(unsigned long EffectID)
{
	for (unsigned int i = 0; i < m_Effects.size(); i++)
	{
		if (m_Effects[i].EffectID == EffectID)
		{
			m_Effects.erase(m_Effects.begin() + i);
			m_CurrentEffects &= ~EffectID;
			return true;
		}
	}

	return false;
}

bool PowerUp::CheckEffect(unsigned long EffectID)
{
	return (m_CurrentEffects & EffectID) ? true : false;
}

void PowerUp::ClearEffects()
{
	m_Effects.clear();
	m_CurrentEffects = 0;
}

bool PowerUp::AddEffectByBit(unsigned char Bit, float Duration)
{
	assert(Bit < 32);
	return AddEffect(Bit2ID(Bit), Duration);
}

bool PowerUp::RemoveEffectByBit(unsigned char Bit)
{
	assert(Bit < 32);
	return RemoveEffect(Bit2ID(Bit));
}

bool PowerUp::CheckEffectByBit(unsigned char Bit)
{
	assert(Bit < 32);
	return CheckEffect(Bit2ID(Bit));
}

unsigned long PowerUp::Tick(float dt)
{
	unsigned long Expired = 0;

	for (unsigned int i = 0; i < m_Effects.size(); i++)
	{
		if (m_Effects[i].Duration < 0.0f) continue;

		m_Effects[i].Duration -= dt;
		if (m_Effects[i].Duration <= 0.0f) {
			m_CurrentEffects &= ~ m_Effects[i].EffectID;
			Expired |= m_Effects[i].EffectID;
			m_Effects.erase(m_Effects.begin() + i);
		}
	}

	return Expired;
}
